package jehc.cloud.oauth.publisher;

import cn.hutool.core.collection.CollectionUtil;
import jehc.cloud.common.util.SpringUtils;
import jehc.cloud.oauth.constant.Constant;
import jehc.cloud.oauth.vo.ChannelEntity;
import jehc.cloud.oauth.vo.Transfer;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Map;

/**
 * @Desc
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Slf4j
public class Publisher extends Thread{
    String token;

    public Publisher(){

    }

    public Publisher(String token){
        this.token = token;
    }

    /**
     * 执行线程
     */
    public void run() {
       NettyUtil nettyUtil = SpringUtils.getBean(NettyUtil.class);
       ChannelUtil channelUtil = SpringUtils.getBean(ChannelUtil.class);

        Map<String,ChannelEntity> map = channelUtil.getChannelConcurrentHashMap();
        if(CollectionUtil.isEmpty(map)){
           return;
        }
        Iterator<Map.Entry<String, ChannelEntity>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, ChannelEntity> entry = entries.next();
            ChannelEntity channelEntity = entry.getValue();
            channelEntity.getRequestInfo().setData(new Transfer(token, Constant.OAUTH_CHANGED));
            boolean res = nettyUtil.sendMessage(entry.getValue());
            log.info("发布Token至客户端. 发送结果：{}-Token：{}",res,token);
        }
    }
}
